package com.hlj.ncp.warehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlj.ncp.warehouse.entity.Stock;
import com.hlj.ncp.warehouse.mapper.StockMapper;
import com.hlj.ncp.warehouse.service.IStockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 库存信息Service业务层处理
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    /**
     * 查询库存信息列表
     * 
     * @param stock 库存信息
     * @return 库存信息
     */
    @Override
    public List<Stock> selectStockList(Stock stock) {
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        if (stock != null) {
            // 条件过滤
            if (stock.getProductId() != null) {
                queryWrapper.eq(Stock::getProductId, stock.getProductId());
            }
            if (stock.getWarehouseId() != null) {
                queryWrapper.eq(Stock::getWarehouseId, stock.getWarehouseId());
            }
            if (stock.getZoneId() != null) {
                queryWrapper.eq(Stock::getZoneId, stock.getZoneId());
            }
            if (stock.getShelfId() != null) {
                queryWrapper.eq(Stock::getShelfId, stock.getShelfId());
            }
            if (stock.getBatchNo() != null) {
                queryWrapper.eq(Stock::getBatchNo, stock.getBatchNo());
            }
            if (stock.getStatus() != null) {
                queryWrapper.eq(Stock::getStatus, stock.getStatus());
            }
        }
        return list(queryWrapper);
    }

    /**
     * 查询库存信息详细
     * 
     * @param stockId 库存ID
     * @return 库存信息
     */
    @Override
    public Stock selectStockById(Long stockId) {
        return getById(stockId);
    }

    /**
     * 新增库存信息
     * 
     * @param stock 库存信息
     * @return 结果
     */
    @Override
    public boolean insertStock(Stock stock) {
        return save(stock);
    }

    /**
     * 修改库存信息
     * 
     * @param stock 库存信息
     * @return 结果
     */
    @Override
    public boolean updateStock(Stock stock) {
        return updateById(stock);
    }

    /**
     * 批量删除库存信息
     * 
     * @param stockIds 需要删除的库存ID
     * @return 结果
     */
    @Override
    public boolean deleteStockByIds(Long[] stockIds) {
        return removeByIds(Arrays.asList(stockIds));
    }

    /**
     * 删除库存信息信息
     * 
     * @param stockId 库存ID
     * @return 结果
     */
    @Override
    public boolean deleteStockById(Long stockId) {
        return removeById(stockId);
    }
    
    /**
     * 入库操作
     * 
     * @param productId 商品ID
     * @param warehouseId 仓库ID
     * @param quantity 入库数量
     * @param batchNo 批次号
     * @return 结果
     */
    @Override
    @Transactional
    public boolean inStock(Long productId, Long warehouseId, BigDecimal quantity, String batchNo) {
        // 检查是否存在相同批次的库存
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Stock::getProductId, productId)
                .eq(Stock::getWarehouseId, warehouseId)
                .eq(Stock::getBatchNo, batchNo);
        Stock stock = getOne(queryWrapper, false);
        
        if (stock != null) {
            // 已存在库存，更新数量
            LambdaUpdateWrapper<Stock> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Stock::getStockId, stock.getStockId())
                    .set(Stock::getQuantity, stock.getQuantity().add(quantity))
                    .set(Stock::getAvailableQuantity, stock.getAvailableQuantity().add(quantity));
            return update(updateWrapper);
        } else {
            // 不存在库存，新增
            Stock newStock = new Stock();
            newStock.setProductId(productId);
            newStock.setWarehouseId(warehouseId);
            newStock.setQuantity(quantity);
            newStock.setAvailableQuantity(quantity);
            newStock.setLockedQuantity(new BigDecimal("0"));
            newStock.setBatchNo(batchNo);
            newStock.setStatus("0"); // 正常状态
            return save(newStock);
        }
    }
    
    /**
     * 出库操作
     * 
     * @param stockId 库存ID
     * @param quantity 出库数量
     * @param reason 出库原因
     * @param remark 备注
     * @return 结果
     */
    @Override
    @Transactional
    public boolean outStock(Long stockId, Integer quantity, String reason, String remark) {
        // 检查库存是否足够
        Stock stock = getById(stockId);
        
        if (stock == null || stock.getQuantity().compareTo(new BigDecimal(quantity)) < 0) {
            // 库存不足
            return false;
        }
        
        // 更新库存
        Stock updateStock = new Stock();
        updateStock.setStockId(stockId);
        updateStock.setQuantity(stock.getQuantity().subtract(new BigDecimal(quantity)));
        updateStock.setLastOutTime(LocalDateTime.now());
        updateStock.setRemark(remark);
        
        return updateById(updateStock);
    }
    
    /**
     * 获取总库存价值
     * 
     * @return 总库存价值
     */
    @Override
    public Double getTotalStockValue() {
        // 查询所有库存
        List<Stock> stockList = list();
        
        double totalValue = 0.0;
        for (Stock stock : stockList) {
            if (stock.getQuantity() != null && stock.getPrice() != null) {
                totalValue += stock.getQuantity().doubleValue() * stock.getPrice().doubleValue();
            }
        }
        
        return totalValue;
    }
    
    /**
     * 获取库存预警数量
     * 
     * @return 预警库存数量
     */
    @Override
    public long getLowStockCount() {
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(Stock::getQuantity, 0)
                .isNotNull(Stock::getWarningQuantity)
                .apply("quantity <= warning_quantity");
        
        return count(queryWrapper);
    }
    
    /**
     * 获取缺货商品数量
     * 
     * @return 缺货商品数量
     */
    @Override
    public long getOutOfStockCount() {
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(Stock::getQuantity, 0);
        
        return count(queryWrapper);
    }
} 